package edu.nyp.locationservicesapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import edu.nyp.locationservicesapp.R;
import edu.nyp.locationservicesapp.application.LauncherModel;
import edu.nyp.locationservicesapp.base.BaseActivity;
import edu.nyp.locationservicesapp.constant.IPreferencesIds;
import edu.nyp.locationservicesapp.utils.NetWorkUtils;
import edu.nyp.locationservicesapp.utils.StringUtils;
import edu.nyp.locationservicesapp.utils.ToastUtil;

/**
 * 应用登录界面
 * Created by Shark on 2017/10/23.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private EditText mEditTextUserName;
    private EditText mEditTextPassword;
    private boolean mCurrentState;//密码输入框是否显示密文
    private ImageView mDelete, mPassHide;
    private CheckBox mCheckBoxProtocol;
    private Button mBtnLogin;
    private TextView mTvRegisterUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initView() {
        mEditTextUserName = (EditText) findViewById(R.id.et_user_phone);
        mEditTextPassword = (EditText) findViewById(R.id.et_password);
        mPassHide = (ImageView) findViewById(R.id.login_password_hide_img);
        mDelete = (ImageView) findViewById(R.id.login_user_delete);
        mCheckBoxProtocol = (CheckBox)findViewById(R.id.cb_use_protocol);
        TextView tvProtocol = (TextView)findViewById(R.id.login_use_protocol);
        mBtnLogin = (Button)findViewById(R.id.btn_login);
        tvProtocol.setText(Html.fromHtml(getString(R.string.user_read_protocol)));
        mTvRegisterUser = (TextView)findViewById(R.id.register_user);
        mCheckBoxProtocol.setOnCheckedChangeListener(this);
        mDelete.setOnClickListener(this);
        mDelete.setVisibility(View.GONE);
        mEditTextUserName.addTextChangedListener(mUserTextWatcher);
        mEditTextUserName.setOnFocusChangeListener(focusChangeListener);
    }
    
    private void initData() {
        String user = LauncherModel.getInstance().getSPManager().getString(IPreferencesIds.USER_LOGIN_PHONE, "");
        if (!TextUtils.isEmpty(user)) {
            mEditTextUserName.setText(user);
            String string = mEditTextUserName.getText().toString();
            mEditTextUserName.setSelection(string.length());
        }
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        initData();
        mTvRegisterUser.setClickable(true);
    }
    
    private TextWatcher mUserTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s == null || s.length() == 0) {
                mDelete.setVisibility(View.GONE);
                return;
            } else {
                mDelete.setVisibility(View.VISIBLE);
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                if (i == 3 || i == 8 || s.charAt(i) != ' ') {
                    sb.append(s.charAt(i));
                    if ((sb.length() == 4 || sb.length() == 9)
                            && sb.charAt(sb.length() - 1) != ' ') {
                        sb.insert(sb.length() - 1, ' ');
                    }
                }
            }
            if (!sb.toString().equals(s.toString())) {
                int index = start + 1;
                if (sb.charAt(start) == ' ') {
                    if (before == 0) {
                        index++;
                    } else {
                        index--;
                    }
                } else {
                    if (before == 1) {
                        index--;
                    }
                }
                mEditTextUserName.setText(sb.toString());
                mEditTextUserName.setSelection(index);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    private View.OnFocusChangeListener focusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                mDelete.setVisibility(View.GONE);
            } else {
                String et = mEditTextUserName.getText().toString();
                if (et.length() > 0)
                    mDelete.setVisibility(View.VISIBLE);
            }
        }
    };

    private void toMainActivity() {
        String user = mEditTextUserName.getText().toString();
        String number = StringUtils.getFormatNumber(user);
        if (TextUtils.isEmpty(number)) {
            ToastUtil.showShortToast(this, getString(R.string.login_error));
            return;
        }
        Intent intent = new Intent(this, EventLocationActivity.class);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.activity_in_from_right, R.anim.activity_out_from_left);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_password_hide_img:
                doHideAction();
                break;
            case R.id.login_user_delete:
                if (mEditTextUserName != null) {
                    mEditTextUserName.setText("");
                }
                break;
            case R.id.register_user:
                mTvRegisterUser.setClickable(false);
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.activity_in_from_right, R.anim.activity_out_from_left);
                break;
            case R.id.btn_login:
                doLogin();
                break;
            default:
                break;
        }
    }

    private void doLogin() {
        String number = StringUtils.getFormatNumber(mEditTextUserName.getText().toString().trim());
        if (TextUtils.isEmpty(number)) {
            ToastUtil.showShortToast(this, getString(R.string.phone_empty));
            return;
        }
        String password = mEditTextPassword.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            ToastUtil.showShortToast(this, getString(R.string.password_empty));
            return;
        }
        if (!NetWorkUtils.isNetworkConnected(this)) {
            ToastUtil.showShortToast(this, getString(R.string.intent_connected_error));
            return;
        }
        String savePassword = LauncherModel.getInstance().getSPManager().getString(number, "");
        if(TextUtils.isEmpty(savePassword)){
            ToastUtil.showShortToast(this, getString(R.string.user_no_reg));
            return;
        }
        if(!savePassword.equals(password)){
            ToastUtil.showShortToast(this, getString(R.string.password_error));
            return;
        }
        LauncherModel.getInstance().getSPManager().commitBoolean(IPreferencesIds.USER_IS_LOGIN, true);
        mBtnLogin.setClickable(false);
        toMainActivity();
    }

    private void doHideAction() {
        mPassHide.setEnabled(false);
        if (mCurrentState) {
            mEditTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            mPassHide.setImageResource(R.mipmap.login_pass_hide);
        } else {
            mEditTextPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            mPassHide.setImageResource(R.mipmap.login_pass_see);
        }
        mCurrentState = !mCurrentState;
        mEditTextPassword.postInvalidate();
        String pass = mEditTextPassword.getText().toString();
        mEditTextPassword.setSelection(pass.length());
        mPassHide.setEnabled(true);
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

    }
}
